package com.example.ex8

import android.content.Intent
import android.os.Bundle
import android.util.Log
import android.widget.ArrayAdapter
import androidx.activity.ComponentActivity
import com.example.ex8.databinding.ActivityMainBinding
import com.google.gson.Gson
import com.google.gson.reflect.TypeToken
import java.io.BufferedReader
import java.io.InputStreamReader
import kotlin.concurrent.thread

class MainActivity : ComponentActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        val binding = ActivityMainBinding.inflate(layoutInflater)
        setContentView(R.layout.activity_main)
        thread {
            val str = readFileFromRaw(R.raw.citycode)
            var gson = Gson()
            val CityType = object : TypeToken<List<City>>() {}.type
            var cities: List<City> = gson.fromJson(str, CityType)
            cities = cities.filter { it.city_code != "" }

            runOnUiThread {
                val adapter = ArrayAdapter<City>(this, android.R.layout.simple_list_item_1, cities)
                binding.listView.adapter = adapter
                binding.listView.setOnItemClickListener { _, _, position, _ ->
                    val cityCode = cities[position].city_code
                    val intent = Intent(this,MainActivity2::class.java)
                    intent.putExtra("cityCode",cityCode)
                    startActivity(intent)
                }
            }

            Log.d("MainActivity", "$cities")
        }


    }

    fun readFileFromRaw(rawName: Int): String? {
        try {
            val inputReader = InputStreamReader(resources.openRawResource(rawName))
            val bufReader = BufferedReader(inputReader)
            var line: String? = ""
            var result: String? = ""
            while (bufReader.readLine().also({ line = it }) != null) {
                result += line
            }
            return result
        } catch (e: Exception) {
            e.printStackTrace()
        }
        return ""
    }
}

